package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.SensitiveWordUtil;
import com.heima.media.dto.ArticleDto;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmSensitive;
import com.heima.media.entity.WmUser;
import com.heima.media.feign.ArticleFeign;
import com.heima.media.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Mr_Su
 * @version v1.0
 * @date 2022/7/1 14:57
 * @desciption
 */
@Service
@Slf4j
public class IAuditServiceImpl implements IAuditService {

    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private IWmNewsService wmNewsService;
    @Autowired
    private MinIOService minIOService;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private IWmUserService wmUserService;
    @Autowired
    private IWmChannelService wmChannelService;

    @Override
    public void audit(Integer newsId) {
        WmNews wmNews = wmNewsService.getById(newsId);
        audit(wmNews);
    }

    @Override
    @Async
    public void audit(WmNews wmNews) {
        boolean isPass = true;

        // 自管理敏感词的审核
        isPass = checkSensitive(wmNews);
        if (!isPass) return;
        
        // 审核文本内容
        isPass = checkText(wmNews);
        if (!isPass) return;
        // 审核图片内容
        isPass = checkImage(wmNews);
        if (!isPass) return;

        // 审核通过,远程调用feign,保存article
        // 判断现在的时间是不是已经到达了发布时间
        if (System.currentTimeMillis() > wmNews.getPublishTime().getTime()){
            // 远程调用feign,保存article
            Long articleId = saveApArticle(wmNews);
            wmNews.setArticleId(articleId);
            wmNews.setStatus(9); // 审核通过,待发布
            wmNewsService.updateById(wmNews);
        }else {
            wmNews.setStatus(8); // 审核通过,待发布
            wmNewsService.updateById(wmNews);

            // 使用Redisson实现延迟发布任务
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque("news-dqueue");
            // 根据blockingDeque获取延迟队列
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            // 放入数据
            long time = wmNews.getPublishTime().getTime() - System.currentTimeMillis();
            delayedQueue.offer(wmNews.getId(),time, TimeUnit.MILLISECONDS);

            log.info("延迟消息发送成功,预计会在 " + time + " 秒后, 会执行一个方法!" + new Date());
        }

    }

    @Autowired
    private IWmSensitiveService wmSensitiveService;
    @Autowired
    private RedissonClient redissonClient;

    private boolean checkSensitive(WmNews wmNews) {
        // 1.初始化DFA算法的map
        List<WmSensitive> wmSensitiveList = wmSensitiveService.list();
//        List<String> stringList = wmSensitiveList.stream().map(s -> s.getSensitives()).collect(Collectors.toList());
        // 等同于上面一行代码
        List<String> stringList = new ArrayList<>();
        for (WmSensitive wmSensitive : wmSensitiveList) {
            stringList.add(wmSensitive.getSensitives());
        }
        SensitiveWordUtil.initMap(stringList);
        // 2.检查文章文本中是否包含敏感词
        // text变量中保存的是 文章标题+文章内容
        String text = wmNews.getTitle();
        String wmNewsContent = wmNews.getContent();
        List<ContentDto> contentDtoList = JSON.parseArray(wmNewsContent, ContentDto.class);
        for (ContentDto contentDto : contentDtoList) {
            if (contentDto.getType().equals("text")){
                text += contentDto.getValue();
            }
        }
        Map<String, Integer> matchWordsMap = SensitiveWordUtil.matchWords(text);
        if (matchWordsMap.size() == 0) {
            return true; // 审核通过
        }else {
            wmNews.setStatus(2);
            Set<String> strings = matchWordsMap.keySet();
            String reason = String.join(",", strings);
            wmNews.setReason("自管理敏感词审核不通过,原因是内容中包含: " + reason);
            wmNewsService.updateById(wmNews);
            return false; // 审核驳回
        }
    }



    public Long saveApArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);

        // app用户可以申请成自媒体用户,自媒体用户自动就是文章作者
        // 获取自媒体用户，自媒体用户中有AuthorId
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        dto.setAuthorId(wmUser.getApAuthorId());
        dto.setAuthorName(wmUser.getName());
        dto.setChannelId(wmNews.getChannelId());
        WmChannel wmChannel = wmChannelService.getById(wmNews.getChannelId());
        dto.setChannelName(wmChannel.getName());
        dto.setLayout(wmNews.getType());
        dto.setFlag(0); //普通文章

        String images = wmNews.getImages();
        List<ImageDto> imageDtoList = JSON.parseArray(images, ImageDto.class);
        List<String> urlList = new ArrayList<>();
        for (ImageDto imageDto : imageDtoList) {
            urlList.add(imageDto.getUrl());
        }
        dto.setImages(String.join(",",urlList));
        dto.setLabels(wmNews.getLabels());
        dto.setPublishTime(wmNews.getPublishTime());
        return articleFeign.saveArticle(dto).getData();
    }

    private boolean checkImage(WmNews wmNews) {
        // 审核内容包含: 1.文章封面图片 2.文章内容中的图片
        // 获取封面图片
        List<ImageDto> imageDtoList = JSON.parseArray(wmNews.getImages(), ImageDto.class);
        // 获取文章内容中的图片
        String content = wmNews.getContent();
        List<ContentDto> contentDtoList = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtoList) {
            if (contentDto.getType().equals("image")){
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());

                if (!imageDtoList.contains(imageDto)){
                    imageDtoList.add(imageDto);
                }
            }
        }

        // 此时imageDtoList已经包含封面和内容中的全部图片
        try {
            List<byte[]> imageList = new ArrayList<>();
            // 图片下载,下载后上传到阿里云
            for (ImageDto imageDto : imageDtoList) {
                InputStream inputStream = minIOService.download(imageDto.getUrl());
                byte[] bytes = IOUtils.toByteArray(inputStream);
                imageList.add(bytes);
            }
            Map map = greenImageScan.imageScan(imageList);
            String suggestion = (String) map.get("suggestion");
            /**
             * - pass：图片正常，可以直接放行。
             * - review：图片需要进一步人工审核。
             * - block：图片违规，可以直接删除或者限制公开
             */
            switch (suggestion) {
                case "pass":{
                    return true;
                }
                case "review":{
                    // 修改自媒体文章的状态和原因
                    wmNews.setStatus(3);
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云图片审核需要人工介入,原因是: " + label);
                    wmNewsService.updateById(wmNews);
                    return false;
                }
                case "block":{
                    // 修改自媒体文章的状态和原因
                    wmNews.setStatus(2);
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云图片审核不通过,原因是: " + label);
                    wmNewsService.updateById(wmNews);
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return false;
    }

    private boolean checkText(WmNews wmNews) {
        // 审核内容包含: 1.文章标题 2.文章中的内容文本
        // 获取文章标题
        String text = wmNews.getTitle();
        // 获取文章中的内容文本
        String content = wmNews.getContent();
        List<ContentDto> contentDtoList = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtoList) {
            if (contentDto.getType().equals("text")){
                // 文本包括：文章标题+文章的内容
                text += contentDto.getValue();
            }
        }
        try {
            Map map = greenTextScan.greenTextScan(text);
            String suggestion = (String) map.get("suggestion");
            /**
             * - pass：文本正常，可以直接放行。
             * - review：文本需要进一步人工审核。
             * - block：文本违规，可以直接删除或者限制公开
             */
            switch (suggestion) {
                case "pass":{
                    return true;
                }
                case "review":{
                    // 修改自媒体文章的状态和原因
                    wmNews.setStatus(3);
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云文本审核需要人工介入,原因是: " + label);
                    wmNewsService.updateById(wmNews);
                    return false;
                }
                case "block":{
                    // 修改自媒体文章的状态和原因
                    wmNews.setStatus(2);
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云文本审核不通过,原因是: " + label);
                    wmNewsService.updateById(wmNews);
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return false;
    }


}
